<?php


namespace app\admin\system\controller;


use app\admin\system\logic\AttachmentLogic;
use app\common\controller\BaseAdminController;
use app\common\service\ConfigService;
use core\exception\BadException;
use core\utils\RandomUtil;
use OSS\OssClient;
use support\Log;
use Throwable;

/**
 * Class UploadController
 * @package app\admin\system\controller
 */
class UploadController extends BaseAdminController
{
    protected $noNeedRight = ['*'];

    public function uploadFile()
    {
        $file = request()->file("file");
        $add_attach = input("add_attach", 1);
        $folderName = input("folderName", "default");
        $date = date("Ymd");
        $uuid = RandomUtil::UUID();
        $path = "/upload/{$folderName}/{$date}/{$uuid}" . "." . $file->getUploadExtension();
        $config = ConfigService::getConfig("FILE_UPLOAD_CONFIG");
        $mode = $config['mode'] ?? "local";
        $domain = $config['domain'] ?? "";
        if ($mode == 'local') {
            $filePath = public_path() . $path;
            if ($file && $file->isValid()) {
                $file->move($filePath);
            }
        } else {
            $accessKeyId = $config['accessKeyId'];
            $accessKeySecret = $config['accessKeySecret'];
            $endpoint = $config['endpoint'];
            $oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            try {
                if ($file && $file->isValid()) {
                    $oss->putObject($config['bucket'], ltrim($path, '/'), file_get_contents($file->getRealPath()));
                }
            } catch (Throwable  $exception) {
                throw new BadException("OSS上传失败:" . $exception->getMessage());
            }
        }

        if ($add_attach) {
            $category_id = input('category_id', 0);
            //添加附件
            $insert = [
                "category_id" => $category_id,
                "name" => $file->getUploadName(),
                "type" => in_array($file->getUploadExtension(), ['jpg', "jpeg", 'webp', 'png', 'gif']) ? 'img' : "file",
                "url" => $domain . $path,
            ];
            try {
                (new AttachmentLogic())->insert($insert);
            } catch (Throwable  $exception) {
                Log::error("文件上传添加附件失败:" . $exception->getMessage());
            }
        }

        return $this->success([
            'fileName' => $file->getUploadName(),
            'fileUploadPath' => $domain . $path
        ]);
    }
}